/**
 * @title : 组织机构 js操作
 * @author : Wuzhiliang
 * @date ： 2013-08-06
 */
var manager;//组织机构列表数据显示Grid
var treeManger;//组织机构树
var $modal = $('#ajax-modal');
var btnAddNew = $("#btnAddNew");
var btnStart = $("#btnStart");
var btnStop = $("#btnStop");
var btnDel = $("#btnDel");

$(function () {
    btnAddNew.click(function (e) {
        addNew();
    });
    btnStart.click(function (e) {
        start();
    });
    btnStop.click(function (e) {
        stop();
    });
    btnDel.click(function (e) {
        del();
    });
    initData();
});

/**
 * 加载页面列表数据
 */
function initData() {
    $.ajax({
        type: "post",
        url: _path + "/organ/findOrganList",
        success: function (data) {
            manager = $("#maingrid").ligerGrid({
                rowHeight: 36,
                headerRowHeight: 38,
                checkbox: true,
                selectRowButtonOnly: true,
                width: '98%',
                height: '98%',
                columns: [
                    { display: 'ID', name: 'id', width: '0%', align: 'left', hide: true},
                    { display: '机构名称', name: 'organame', width: '20%', align: 'left', render: function (row) {
                        return "<a href='javascript:show(\"" + row.id + "\")' id='show'>" + row.organame + "</a>";
                    }},
                    { display: '状态', name: 'isactive', width: '9%', type: 'int', align: 'center', render: function (row) {
                        if (row.isactive == "1") {
                            return "<i class='fa fa-check'></i>";
                        } else {
                            return "<i class='fa fa-frown-o'></i>";
                        }
                    }},
                    { display: '顺序', name: 'sort', width: '9%', type: 'int', align: 'center' },
                    { display: '备注', name: 'remark', width: '42.8%', align: 'center' }
                ], data: data, tree: { columnName: 'organame', idField: 'id', parentIDField: 'pid' }, pageSize: 20, rownumbers: true, pageParmName: "curNo", pagesizeParmName: "curSize"

            });
        }
    });
    $("#pageloading").hide();
}

//------详细信息修改-----
/**
 * @title : 以树的形式展示机构
 * */
function initOgrTree() {
    var url = _path + "/organ/organTree";
    $.ajax({
        type: "post",
        url: url,
        async: false,
        success: function (data) {
            var treeData = [];
            treeData.push({
                'id': '999999',
                'icon': '',
                'text': '机构列表',
                'isexpand': true,
                'pid': ""
            });
            var orgList = data.orgList;
            for (var i = 0; i < orgList.length; i++) {
                treeData.push({
                    'id': orgList[i].id,
                    'icon': '',
                    'text': orgList[i].organame,
                    'isexpand': true,
                    'pid': orgList[i].pid
                });
            }
            loadTree(treeData);
        }
    });
}

//加载树
function loadTree(dataTree) {
    var $$ = $("#orgTree");
    $$.html("<div style='height: 260px;overflow-y: auto'></div>");
    treeManger = $$.children().ligerTree({
        data: dataTree,
        idFieldName: 'id',
        parentIDFieldName: 'pid',
        checkbox: false,
        slide: true,
        nodeWidth: 130,
        onSelect: onSelect
    });
    var nodeId = $("#pid").val();
    if (nodeId != '-1' && nodeId != '') {
        var data = treeManger.getDataByID(nodeId);
        onclickPass(data);
        treeManger.selectNode(nodeId);
    }
}
function onSelect(note) {
    onclickPass(note.data);
}
function onclickPass(data) {
    var orgId = data.id;
    var porganame = data.text;
    if (orgId != $("#id").val()) {
        if (orgId == "-1") {
            $("#pid").val("999999");
            $("#porganame").val("机构列表");
        } else {
            $("#pid").val(orgId);
            $("#porganame").val(porganame);
        }
    }
}

/**
 * @title : 新增详细信息
 */
function addNew() {
    removeDetail();
    initOgrTree();
    $modal.modal('show');

}

/**
 * @title : 查看详细信息
 */
function show(organId) {
    App.ajax(_path + "/organ/forEditOrgan", "id=" + organId, detail);

}

function detail(data) {
    $("#id").val(data.id);
    $("#organame").val(data.organame);
    $("#pid").val(data.pid);
    $("#porganame").val(data.porganame);
    $("#sort").val(data.sort);
    $(":radio[value='" + data.isactive + "']").attr("checked", "checked");
    $("#remark").val(data.remark);
    initOgrTree();

    $modal.modal('show');

}

function removeDetail(data) {
    $(':input', '#formDetail')
        .not(':button, :submit, :reset,:radio')
        .val('').removeAttr('checked').removeAttr('selected');
}

function save() {
    if (validation()) { // 校验提交
        App.ajax(_path + "/organ/forSaveOrUpdOrgan", $("#formDetail").serialize(), saveResult);
    }
}
function saveResult(data) {
    if (data == '200') {
        $modal.modal('hide');
        window.location.reload();
    } else {
        App.bubble(500, "保存失败！");
    }
}

/**
 * 校验input
 * @return
 */
function validation() {
    var pid = $("#formDetail #pid").val();
    if (pid.replace(/(^\s*)|(\s*$)/, "").length == 0) {
        App.bubble(500, "请选择上级机构！");
        return false;
    }
    var organame = $("#formDetail #organame").val();
    if (organame.replace(/(^\s*)|(\s*$)/, "").length == 0) {
        App.bubble(500, "机构名称不能为空！");
        return false;
    }
    var remark = $("#formDetail #remark").val();
    var length = remark.replace(/[^\x00-\xff]/g, "**").length;//
    if (length > 256) {
        App.bubble(500, "备注长度不能大于128个英文字符或者多于64个中文字符！");
        return false;
    }
    return true;
}

/**
 * 启用机构
 * @return
 */
function start() {
    updOrgStatus('1');
}
/**
 * 停用机构
 * @return
 */
function stop() {
    updOrgStatus('0');
}
/**
 * 机构启用和停用操作
 * @return
 */
function updOrgStatus(isactive) {
    var organIds = '';
    //获取选中记录行
    var rowid = manager.getSelecteds();
    var length = rowid.length;
    if (length == 0) {
        App.bubble(500, "请选择要启用或停用的机构记录！");
        return false;
    } else if (length > 0) {
        var url = _path + "/organ/updOrgStatus";
        //获取需要操作的用户ID
        for (var i = 0; i < length; i++) {
            if (i < length - 1) {
                organIds += rowid[i].id + ",";
            } else {
                organIds += rowid[i].id;
            }
        }
        $.ajax({
            type: "post",
            url: url,
            data: {
                "organIds": organIds,
                "isactive": isactive
            },
            success: function (data) {
                //如果删除成功，则刷新页面！
                if (data["msg"] == "success" && isactive == "1") {
                    App.bubble(200, "机构启用成功！");
                } else if (data["msg"] == "error" && isactive == "1") {
                    App.bubble(500, "机构启用失败！");
                } else if (data["msg"] == "success" && isactive == "0") {
                    App.bubble(200, "机构停用成功！");
                } else if (data["msg"] == "error" && isactive == "0") {
                    App.bubble(500, "机构停用失败！");
                } else {
                    App.bubble(500, data["msg"]);
                }
                //启用、停用后列表刷新
                manager.set({url: _path + "/organ/findOrganList"});
            },
            error: function () {
                App.bubble(500, "启用、停用机构信息失败！");
            }
        });
    }
}
/**
 * 删除机构
 * @return
 */
function del() {
    var organIds = '';
    //获取选中记录行
    var rowid = manager.getSelecteds();
    var length = rowid.length;
    if (length == 0) {
        App.bubble(500, "请选择一条要删除的机构记录！");
        return false;
    } else {
        if (manager.hasChildren(rowid[0])) {
            if (confirm(rowid[0].organame + "有子组织机构是否删除？",
                function (yes) {
                    if (!yes) {
                        return false;
                    }
                }));
        }else{
        	layer.confirm('您确定要删除吗？', function(){
        		delOrgans(rowid[0].id);
    		}, function(){
    		
    		});
        } 
    }
}

function delOrgans(organIds) {
    $.ajax({
        type: "post",
        url: _path + "/organ/delOrgan",
        data: {
            "organIds": organIds
        },
        success: function (data) {
            //如果删除成功，则刷新页面！
            if (data["msg"] == "success") {
                App.bubble(200, "机构删除成功！");
            } else if (data["msg"] == "error") {
                App.bubble(500, "机构删除失败！");
            } else {
                App.bubble(500, data["msg"]);
            }
            //启用、停用后列表刷新
            manager.set({url: _path + "/organ/findOrganList"});
        },
        error: function () {
            App.bubble(500, "机构删除失败！");
        }
    });
}

	